package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 准备一个容器保存多个客户端
 * 服务端申请一个端口号 启动成功
 * 找个助手开始干事儿服务端准备读取和转发的流（这个要存下来）
 * 记得关流/调用start/行刷新，要写true
 */
public class SimpleChatServer {
    //准备一个容器保存多个客户端
    private List<PrintWriter> allOuts = new ArrayList<>();
    public SimpleChatServer() throws Exception {
        //服务端申请一个端口号 启动成功
        ServerSocket server = new ServerSocket(8080);
        System.out.println("服务已经启动成功");
        while (true) {
            Socket socket = server.accept();
            System.out.println("一个用户已连接");
            //找个助手开始干事儿服务端准备读取和转发的流（这个要存下来）
            ClientHandler clientHandler = new ClientHandler(socket);
            clientHandler.start();
        }
    }
    class ClientHandler extends Thread{
        private Socket socket;
        public ClientHandler(Socket socket)
        {
            this.socket = socket;
        }
        public void run()
        {
            //准备接受的流
            try{
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                //准备写出去的流
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);
                //添加写出流对象（客户）到集合 保存接受到的流
                synchronized (allOuts) {
                    allOuts.add(pw);
                }
                //持续读入 群发写出
                String line = null;
                while ((line = br.readLine()) != null){
                    System.out.println(line);
                    for (PrintWriter printWriter : allOuts){
                        printWriter.println(line);
                    }
                }
                //关流
                br.close();
                pw.close();
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }
    public static void main(String[] args) throws Exception {
        ChatServer01 chatServer =  new ChatServer01();
    }
}
